package com.shiro.entity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.util.CollectionUtils;


/**
 * 角色
 * 
 * @author erich
 * @version 1.0
 * @created 01-12-2013 16:36:04
 */

public class Role extends IdEntity {

	private String code;
	private String name;
	
	private String app;

	@DBRef
	private List<Permission> permissions;
	
	public Role() {
	}
	
	public Role(String id) {
		setId(id);
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Permission> getPermissions() {
		if (CollectionUtils.isEmpty(permissions)) {
			return null;
		}
		List<Permission> result = new ArrayList<Permission>();
		for(Permission item: permissions){
			if (item!=null&&!item.getDelflag()){
				result.add(item);
			}
		}
		return result;
	}

	public Set<String> getPermissionCodes() {
		Set<String> result = new HashSet<String>();
		
		if(this.getPermissions()!=null){
			for(Permission item: this.getPermissions()){
				result.add(item.getFuncCode());
			}
		}
		return result;
	}
	
	public void setPermissions(List<Permission> permissions) {
		this.permissions = permissions;
	}

	public String getPermissionView() {
		if (CollectionUtils.isEmpty(getPermissions())) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		int lineNo = 1;
		for (Permission permission : permissions) {
			if (null == permission || null == permission.getModule()) {
				continue;
			}
			if (sb.length() >= 100 * lineNo) {
				sb.append("<br>");
				lineNo++;
			}
			sb.append(permission.getModule().getName());
			sb.append(":");
			sb.append(permission.getFuncName());
			sb.append("|");
		}
		
		return sb.substring(0, sb.length() -1);
	}

	public String getApp() {
		return app;
	}

	public void setApp(String app) {
		this.app = app;
	}
}